<!DOCTYPE html>
<html class="x-admin-sm">

<head>
    <meta charset="UTF-8">
    <title>宿舍管理系统</title>
    <meta name="renderer" content="webkit">
    <meta name="csrf-token" content="{{ csrf_token() }}" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
        content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />
    <link rel="stylesheet" href="{{ asset('css/font.css') }}">
    <link rel="stylesheet" href="{{ asset('css/xadmin.css') }}">
    <script src="{{ asset('lib/layui/layui.js') }}" charset="utf-8"></script>
    <script type="text/javascript" src="{{ asset('js/xadmin.js') }}"></script>
    <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>

<body>
    <div class="x-nav">
        <span class="layui-breadcrumb">
            <a href="/home">首页</a>
            <a>
                <cite>费用列表</cite></a>
        </span>
        <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right"
            onclick="location.reload()" title="刷新">
            <i class="layui-icon layui-icon-refresh" style="line-height:30px"></i></a>
    </div>
    <div class="layui-fluid">
        <div class="layui-row layui-col-space15">
            <div class="layui-col-md12">
                <div class="layui-card">
                    <div class="layui-card-body ">
                        <form class="layui-form layui-col-space5">
                            <div class="layui-inline layui-show-xs-block">
                                <input type="text" name="staffPeriodFeeDetails.dorm.code" placeholder="请输入宿舍号"
                                    autocomplete="off" class="layui-input"
                                    value="{{ old('staffPeriodFeeDetails.dorm.code') }}">
                            </div>
                            <div class="layui-inline layui-show-xs-block">
                                <input type="text" name="staff.name" placeholder="请输入姓名" autocomplete="off"
                                    class="layui-input" value="{{ old('staff.name') }}">
                            </div>
                            <div class="layui-inline layui-show-xs-block">
                                <input type="text" name="staff.card_num" placeholder="请输入工牌号" autocomplete="off"
                                    class="layui-input" value="{{ old('staff.card_num') }}">
                            </div>
                            <div class="layui-input-inline layui-show-xs-block">
                                <select name="period_id" lay-search>
                                    <option value="" {{ old('period_id') ? '' : 'selected' }}>周期</option>
                                    @foreach ($periods as $k => $v)
                                        <option value="{{ $k }}"
                                            {{ old('period_id') == $k ? 'selected' : '' }}>
                                            {{ $v }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="layui-inline layui-show-xs-block">
                                <button class="layui-btn" id="btn-search" lay-submit="" lay-filter="search"><i
                                        class="layui-icon">&#xe615;</i></button>
                            </div>
                        </form>
                    </div>
                    <div class="layui-card-body layui-table-body layui-table-main">
                        <table class="layui-hide" id="test" lay-filter="test"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="detail">明细</a>
    @{{# if(d.period_status<2) { }}
    <a class="layui-btn layui-btn-xs" lay-event="adjust_fee">调整</a>
    @{{# } }}

</script>
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-primary layui-btn-sm" lay-event="add">
            <i class="layui-icon">&#xe654;</i>
        </button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" lay-event="update">
            <i class="layui-icon">&#xe642;</i>
        </button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" lay-event="delete">
            <i class="layui-icon">&#xe640;</i>
        </button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" lay-event="export">
            全部导出
        </button>
    </div>
</script>
<script>
    layui.use(['table', 'form'], function() {
        let b = build_criteria();
        let q = asm_query(b)
        let total = 0;
        var table = layui.table;
        let t = table.render({
            elem: '#test',
            url: `/staff-period-fees?${q}`,
            toolbar: '#toolbarDemo',
            title: '费用列表',
            totalRow: true,
            cols: [
                [{
                    type: 'checkbox'
                }, {
                    field: 'id',
                    title: 'ID',
                    width: 80,
                    unresize: true,
                    hide: true
                }, {
                    field: 'company.name',
                    title: '公司',
                    width: 100,
                    templet: function(d) {
                        return d.company.short_name || d.company.name;
                    },
                    hide: {{ Auth::user()->is_super ? 'false' : 'true' }}
                }, {
                    field: 'staff.name',
                    title: '姓名',
                    width: 80
                }, {
                    field: 'department',
                    title: '部门',
                    width: 120
                }, {
                    field: 'position',
                    title: '职务',
                    width: 80
                }, {
                    field: 'staffPeriodFeeDetails.dorm.code',
                    title: '宿舍',
                    width: 80
                }, {
                    field: 'staff.sex',
                    title: '性别',
                    width: 80,
                    hide: true
                }, {
                    field: 'staff.id_card',
                    title: '身份证',
                    width: 160
                }, {
                    field: 'staff.card_num',
                    title: '工牌号',
                    width: 90
                }, {
                    field: 'period.name',
                    title: '周期',
                    width: 110
                }, {
                    field: 'period.start_date',
                    title: '起始日',
                    width: 100,
                    hide: true
                }, {
                    field: 'period.end_date',
                    title: '截止日',
                    width: 100,
                    hide: true
                }, {
                    field: 'dorm_days',
                    title: '入住天数',
                    width: 100,
                    hide: true
                }, {
                    field: 'water_fee',
                    title: '水费',
                    width: 90,
                    sort: true
                }, {
                    field: 'hot_water_fee',
                    title: '热水费',
                    width: 90,
                    sort: true
                }, {
                    field: 'electric_fee',
                    title: '电费',
                    width: 90,
                    sort: true
                }, {
                    field: 'manage_fee',
                    title: '管理费',
                    width: 90,
                    sort: true
                }, {
                    field: 'deposit_fee',
                    title: '押金',
                    width: 90,
                    sort: true
                }, {
                    field: 'adjust_fee',
                    title: '调整费',
                    width: 90
                }, {
                    field: 'total_fee',
                    title: '合计',
                    width: 100
                }, {
                    field: 'adjust_reason',
                    title: '调整原因',
                    width: 100
                }, {
                    field: 'created_at',
                    title: '创建时间',
                    width: 150,
                    sort: true,
                    hide: true
                }, {
                    field: 'updated_at',
                    title: '更新时间',
                    width: 150,
                    sort: true,
                    hide: true
                }, {
                    fixed: 'right',
                    title: '操作',
                    width: 140,
                    align: 'center',
                    toolbar: '#barDemo'
                }]
            ],
            autoSort: false,
            initSort: {
                field: 'updated_at',
                type: 'desc'
            },
            page: true,
            limit: 20,
            limits: [20, 40, 80, 160, 320, 640, 1280],
            parseData: function(res) { //将原始数据解析成 table 组件所规定的数据
                total = res.data.meta.pagination.total
                return {
                    "code": 0, //解析接口状态
                    "msg": "", //解析提示文本
                    "count": total, //解析数据长度
                    // "count": res.data.total, //解析数据长度
                    "data": res.data.data //解析数据列表
                };
            }
        });
        //触发排序事件
        table.on('sort(test)', function(obj) { //注：sort 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            table.reload('test', {
                initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。
                    ,
                where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                    search: b.criteria,
                    searchJoin: 'and',
                    orderBy: obj.field //排序字段
                        ,
                    sortedBy: obj.type //排序方式
                }
            });
        });

        //监听头工具栏事件
        table.on('toolbar(test)', function(obj) {
            let checkStatus = table.checkStatus(obj.config.id);
            let data = checkStatus.data; //获取选中的数据
            switch (obj.event) {
                case 'add':
                    layer.msg('不能人为添加');
                    break;
                case 'update':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                    } else if (data.length > 1) {
                        layer.msg('只能同时编辑一个');
                    } else {
                        xadmin.open('更新费用', `/staff-period-fees/${data[0].id}/edit`);
                    }
                    break;
                case 'delete':
                    layer.msg('不能人为删除');
                    break;
                case 'export':
                    //使用ajax请求获取所有数据
                    let period_id = $("[name='period_id']").val();
                    if (period_id) {
                        layer.load();
                        $.ajax({
                            url: "/staff-period-fees?export=2&period_id=" + period_id,
                            type: 'get',
                            dataType: 'json',
                            statusCode: {
                                401: function() {
                                    console.log("statusCode 401 called");
                                    window.location.reload();
                                },
                                449: function() {
                                    console.log("statusCode 449 called");
                                }
                            },
                            success: function(res) {
                                //使用table.exportFile()导出数据
                                table.exportFile(t.config.id, res.data.data, 'xls');
                            },
                            complete: function() {
                                layer.closeAll('loading');
                            }
                        });
                    } else {
                        layer.alert('必须选择要导出的周期');
                    }

                    break;
            };
        });

        //监听行事件
        table.on('tool(test)', function(obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            console.log(data);
            let title = `${data['staff.name']} ${data['period.name']} 费用调整`;
            switch (layEvent) {
                case 'adjust_fee':
                    xadmin.open(title, '/staff-period-fees/' + data.id + '/edit');
                    break;
                case 'detail':
                    title = `${data['staff.name']} ${data['period.name']} 费用明细`;
                    xadmin.open(title, '/staff-period-fee-details?search=staff_period_fee_id:' + data
                        .id + "&orderBy=fee_type", 800, 500);
                    break;
            }

        });


        let form = layui.form;
        form.on('submit(search)', function(data) {
            b = build_criteria()
            q = asm_query(b)
            table.reload('test', {
                url: '/staff-period-fees',
                where: {
                    search: b.criteria,
                    searchJoin: 'and'
                },
                page: {
                    curr: 1
                }
            });

            //阻止事件冒泡
            return false;
        });

    });


    function del_one(obj, id) {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            url: 'staff-period-fees/' + id,
            type: 'DELETE',
            dataType: "json",
            statusCode: {
                401: function() {
                    console.log("statusCode 401 called");
                    window.location.reload();
                },
                449: function() {
                    console.log("statusCode 449 called");
                }
            },
            success: function() {
                layer.msg(`已删除${id}!`, {
                    icon: 1,
                    time: 1000
                });
                if (obj) {
                    $(obj).parents("tr").remove();
                }
            },
            error: function(err) {
                layer.msg('删除失败', {
                    icon: 2,
                    time: 1000
                });
            }
        });

    }

    function build_criteria() {
        let dorm_code = $("[name='staffPeriodFeeDetails.dorm.code']").val();
        let staff_name = $("[name='staff.name']").val();
        let card_num = $("[name='staff.card_num']").val();
        let period_id = $("[name='period_id']").val();
        let criteria = '';
        let oprt = '';
        if (dorm_code) {
            criteria += `staffPeriodFeeDetails.dorm.code:${dorm_code};`
        }
        if (staff_name) {
            criteria += `staff.name:${staff_name};`;
        }

        if (card_num) {
            criteria += `staff.card_num:${card_num};`;
        }
        if (period_id) {
            criteria += `period_id:${period_id};`;
        }

        if (criteria)
            criteria = criteria.slice(0, -1);
        return {
            criteria,
            oprt
        }
    }

    function asm_query(build_criteria, order = 'updated_at', sort = 'desc') {
        return `search=${build_criteria.criteria}&searchFields=${build_criteria.oprt}&searchJoin=and&orderBy=${order}&sortedBy=${sort}`
    }
</script>

</html>
